package android.game.BoxedIn;

public class GameRecord {
	public GameRecord() {
		Grid = new int[64];
		Horizontal = new int[72];
		Vertical = new int[72];
		
		reset();
	}
		
	public static final int ClearSpace = 2;
	public static final int PlayerOne = 0;
	public static final int PlayerTwo = 1;
	
	public static final int Top = 0;
	public static final int Bottom = 1;
	public static final int Left = 2;
	public static final int Right = 3;
		
	public final int[] Grid;
	public final int[] Horizontal;
	public final int[] Vertical;
	
	public void reset() {
		for(int c = 0; c < 64; ++c) {
			Grid[c] = ClearSpace;
			Horizontal[c] = ClearSpace;
			Vertical[c] = ClearSpace;
		}
		
		for(int c = 64; c < 72; ++c) {
			Horizontal[c] = ClearSpace;
			Vertical[c] = ClearSpace;
		}
	}
	
	public boolean validTurn(int which, boolean vertical) {
		if(which < 0 || which > 72) {
			return false;
		}
		
		if(vertical) {
			if(Vertical[which] != ClearSpace) {
				return false;
			}
		} else {
			if(Horizontal[which] != ClearSpace) {
				return false;
			}
		}
		
		return true;
	}
	
	public boolean takeTurn(int which, boolean vertical, int player) {
		if(which < 0 || which > 72) {
			return false;
		}
		
		if(vertical) {
			if(Vertical[which] != ClearSpace) {
				return false;
			}
			
			Vertical[which] = player;
			
			
		} else {
			if(Horizontal[which] != ClearSpace) {
				return false;
			}
			
			Horizontal[which] = player;
		}
		
		int location = vertical ? ((which / 9) * 8) + (which % 9) : which;
		int location2 = vertical ? (((which / 9) * 8) + (which % 9)) - 1 : which - 8;
		
		if(location >= 0 && location <= 63) {
			if(getFences(location) == 4) {
				Grid[location] = player;
			}
		}
		if(location2 >= 0 && location2 <= 63) {
			if(getFences(location2) == 4) {
				Grid[location2] = player;
			}
		}
		
		return true;
	}
	
	/*
	 * Get the number of filled fences for a given location.
	 */
	public int getFences(int location) {
		final int left = ((location / 8) * 9) + (location % 8);
		
		return ((Horizontal[location] != ClearSpace) ? 1 : 0) + 
		((Horizontal[location + 8] != ClearSpace) ? 1 : 0) +
		((Vertical[left] != ClearSpace) ? 1 : 0) +
		((Vertical[left + 1] != ClearSpace) ? 1 : 0);
	}
}
